const WebSocket = require('ws');
const crypto = require('crypto');
const moment = require('moment');
const dotenv = require('dotenv');
dotenv.config({ path: '../../../.env' }); // 加载 .env 文件中的环境变量
// 替换为你的真实信息
const APP_ID = process.env.APP_ID;
const API_KEY = process.env.API_KEY;
const API_SECRET = process.env.API_SECRET;
const HOST = 'spark-api.xf-yun.com';
const PATH = '/v3.5/chat';
const WS_URL = `wss://${HOST}${PATH}`;

console.log(APP_ID, API_KEY, API_SECRET);
/** 生成鉴权信息 */
function generateAuth() {
  const date = moment().utc().format('ddd, DD MMM YYYY HH:mm:ss [GMT]');
  const digest = `host: ${HOST}\ndate: ${date}\nGET ${PATH} HTTP/1.1`;

  const signature = crypto.createHmac('sha256', API_SECRET)
    .update(digest)
    .digest('base64');

  const authorization = `api_key="${API_KEY}", algorithm="hmac-sha256", headers="host date request-line", signature="${signature}"`;
  const encodedAuth = Buffer.from(authorization).toString('base64');
  console.log('Digest:', digest); // 调试信息
  console.log('Signature:', signature); // 调试信息
  console.log('Authorization:', authorization); // 调试信息
  console.log('Encoded Authorization:', encodedAuth); // 调试信息
  return {
    authorization: encodedAuth,
    date
  };
}

/** 调用星火大模型 */
// async function callSparkAPI(prompt) {
//   const { authorization, date } = generateAuth();
//   const signUrl = `${WS_URL}?authorization=${authorization}&date=${encodeURIComponent(date)}&host=${HOST}`;

//   return new Promise((resolve, reject) => {
//     const ws = new WebSocket(signUrl);

//     ws.on('open', () => {
//       const requestData = {
//         header: {
//           app_id: APP_ID,
//           uid: 'user_123'
//         },
//         parameter: {
//           chat: {
//             domain: 'generalv3',
//             temperature: 0.7,
//             max_tokens: 2048
//           }
//         },
//         payload: {
//           message: {
//             text: [{ role: 'user', content: prompt }]
//           }
//         }
//       };

//       ws.send(JSON.stringify(requestData));
//     });

//     ws.on('message', (data) => {
//       try {
//         const response = JSON.parse(data.toString());
//         if (response.header.code === 0) {
//           resolve(response.payload.choices.text[0].content);
//         } else {
//           reject(new Error(`模型错误: ${response.header.message} (Code: ${response.header.code})`));
//         }
//       } catch (error) {
//         reject(new Error(`解析错误: ${error.message}`));
//       } finally {
//         ws.close();
//       }
//     });

//     ws.on('error', (error) => {
//       reject(new Error(`连接错误: ${error.message}`));
//     });

//     ws.on('close', () => {
//       console.log('WebSocket 连接已关闭');
//     });
//   });
// }
/** 调用星火大模型 */
async function callSparkAPI(prompt) {
  const { authorization, date } = generateAuth();
  const signUrl = `${WS_URL}?authorization=${authorization}&date=${encodeURIComponent(date)}&host=${HOST}`;

  return new Promise((resolve, reject) => {
    const ws = new WebSocket(signUrl);
    let completeResponse = ""; // 用于拼接完整的响应内容

    ws.on('open', () => {
      const requestData = {
        header: {
          app_id: APP_ID,
          uid: 'user_123' // 可选用户标识
        },
        parameter: {
          chat: {
            domain: 'generalv3', // 3.5 版本领域
            temperature: 0.7,
            max_tokens: 2048
          }
        },
        payload: {
          message: {
            text: [{ role: 'user', content: prompt }]
          }
        }
      };

      ws.send(JSON.stringify(requestData));
    });

    ws.on('message', (data) => {
      try {
        const response = JSON.parse(data.toString());
        if (response.header.code === 0) {
          // 拼接返回的内容
          completeResponse += response.payload.choices.text[0].content;
        } else {
          reject(new Error(`模型错误: ${response.header.message} (Code: ${response.header.code})`));
          ws.close();
        }
      } catch (error) {
        reject(new Error(`解析错误: ${error.message}`));
        ws.close();
      }
    });

    ws.on('close', () => {
      console.log('WebSocket 连接已关闭');
      if (completeResponse) {
        resolve(completeResponse);
      } else {
        reject(new Error('没有接收到有效的响应内容'));
      }
    });

    ws.on('error', (error) => {
      reject(new Error(`连接错误: ${error.message}`));
      ws.close();
    });
  });
}

/** 生成故事 */
module.exports.generateStory = async function generateStory(achievements) {
  console.log(achievements);

  if (!Array.isArray(achievements) || achievements.length === 0) {
    throw new Error('成就数据必须为非空数组');
  }

  const prompt = `请根据以下成就生成一篇连贯的成长故事，要求包含时间和细节：${JSON.stringify(achievements)}`;
  console.log(prompt);

  try {
    return await callSparkAPI(prompt);
  } catch (error) {
    console.error('生成故事失败:', error.message);
    throw error;
  }
};

/** 生成励志名言 */
module.exports.generateQuote = async function generateQuote() {
  const prompt = '请随机提供一条励志的名人名言';
  console.log(prompt);

  try {
    return await callSparkAPI(prompt);
  } catch (error) {
    console.error('生成名言失败:', error.message);
    throw error;
  }
};

/** 生成每日总结 */
module.exports.generateDailySummary = async function generateDailySummary(events) {
  if (!Array.isArray(events) || events.length === 0) {
    throw new Error('每日事件数据必须为非空数组');
  }
  const prompt = `请根据以下今日事件生成一份每日总结：${JSON.stringify(events)}`;
  console.log(prompt);

  try {
    return await callSparkAPI(prompt);
  } catch (error) {
    console.error('生成每日总结失败:', error.message);
    throw error;
  }
};